/*
 [The "BSD license"]
 Copyright (c) 2011-2012 Joel Li (李家智)
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
 3. The name of the author may not be used to endorse or promote products
     derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.bee.tl.core.io;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;

import sun.nio.cs.HistoricallyNamedCharset;

public class OutputStreamByteWriter extends Writer {
	private static final int DEFAULT_BYTE_BUFFER_SIZE = 10;;
	OutputStream out = null;
	private Charset cs;
	private CharsetEncoder encoder;
	private ByteBuffer bb;

	// Leftover first char in a surrogate pair
	private boolean haveLeftoverChar = false;
	private char leftoverChar;
	private CharBuffer lcb = null;

	private volatile boolean isOpen = true;

	public OutputStreamByteWriter(OutputStream out, String charsetName)
			throws UnsupportedEncodingException {
		String csn = charsetName;

		if (!Charset.isSupported(csn))
			throw new UnsupportedEncodingException(csn);
		cs = Charset.forName(csn);

		this.out = out;

		this.encoder = cs.newEncoder()
				.onMalformedInput(CodingErrorAction.REPLACE)
				.onUnmappableCharacter(CodingErrorAction.REPLACE);

		bb = ByteBuffer.allocate(DEFAULT_BYTE_BUFFER_SIZE);

	}

	public void write(byte[] bs) throws IOException {

		if (haveLeftoverChar)
			flushLeftoverChar(null, false);
		int remain = bb.remaining();
		int inputLeft = bs.length;
		if (remain >= inputLeft) {
			bb.put(bs);
			return;
		} else {

			bb.put(bs, 0, remain);
			writeBytes();
			inputLeft = inputLeft - remain;
			int start = remain;
			while (inputLeft > bb.capacity()) {
				bb.put(bs, start, bb.capacity());
				writeBytes();
				inputLeft = inputLeft - bb.capacity();
				start = start + bb.capacity();

			}
			if (inputLeft > 0) {
				bb.put(bs, start, bs.length - start);
			}

		}

	}

	protected OutputStream getOutputStream() {
		return this.out;
	}

	@Override
	public void write(char[] cbuf, int off, int len) throws IOException {
		ensureOpen();
		if ((off < 0) || (off > cbuf.length) || (len < 0)
				|| ((off + len) > cbuf.length) || ((off + len) < 0)) {
			throw new IndexOutOfBoundsException();
		} else if (len == 0) {
			return;
		}
		implWrite(cbuf, off, len);

	}

	@Override
	public void close() throws IOException {
		if (!isOpen)
			return;
		implClose();
		isOpen = false;

	}

	@Override
	public void flush() throws IOException {
		ensureOpen();
		implFlush();

	}

	private void writeBytes() throws IOException {
		bb.flip();
		int lim = bb.limit();
		int pos = bb.position();
		assert (pos <= lim);
		int rem = (pos <= lim ? lim - pos : 0);

		if (rem > 0) {
			out.write(bb.array(), bb.arrayOffset() + pos, rem);
		}
		bb.clear();
	}

	private void flushLeftoverChar(CharBuffer cb, boolean endOfInput)
			throws IOException {
		if (!haveLeftoverChar && !endOfInput)
			return;
		if (lcb == null)
			lcb = CharBuffer.allocate(2);
		else
			lcb.clear();
		if (haveLeftoverChar)
			lcb.put(leftoverChar);
		if ((cb != null) && cb.hasRemaining())
			lcb.put(cb.get());
		lcb.flip();
		while (lcb.hasRemaining() || endOfInput) {
			CoderResult cr = encoder.encode(lcb, bb, endOfInput);
			if (cr.isUnderflow()) {
				if (lcb.hasRemaining()) {
					leftoverChar = lcb.get();
					if (cb != null && cb.hasRemaining())
						flushLeftoverChar(cb, endOfInput);
					return;
				}
				break;
			}
			if (cr.isOverflow()) {
				assert bb.position() > 0;
				writeBytes();
				continue;
			}
			cr.throwException();
		}
		haveLeftoverChar = false;
	}

	void implWrite(char cbuf[], int off, int len) throws IOException {
		CharBuffer cb = CharBuffer.wrap(cbuf, off, len);

		if (haveLeftoverChar)
			flushLeftoverChar(cb, false);

		while (cb.hasRemaining()) {
			CoderResult cr = encoder.encode(cb, bb, false);
			if (cr.isUnderflow()) {
				assert (cb.remaining() <= 1) : cb.remaining();
				if (cb.remaining() == 1) {
					haveLeftoverChar = true;
					leftoverChar = cb.get();
				}
				break;
			}
			if (cr.isOverflow()) {
				assert bb.position() > 0;
				writeBytes();
				continue;
			}
			cr.throwException();
		}
	}

	void implFlushBuffer() throws IOException {
		if (bb.position() > 0)
			writeBytes();
	}

	void implFlush() throws IOException {
		implFlushBuffer();
		if (out != null)
			out.flush();
	}

	void implClose() throws IOException {
		flushLeftoverChar(null, true);
		try {
			for (;;) {
				CoderResult cr = encoder.flush(bb);
				if (cr.isUnderflow())
					break;
				if (cr.isOverflow()) {
					assert bb.position() > 0;
					writeBytes();
					continue;
				}
				cr.throwException();
			}

			if (bb.position() > 0)
				writeBytes();
			out.close();
		} catch (IOException x) {
			encoder.reset();
			throw x;
		}
	}

	String encodingName() {
		return ((cs instanceof HistoricallyNamedCharset) ? ((HistoricallyNamedCharset) cs)
				.historicalName() : cs.name());
	}

	private void ensureOpen() throws IOException {
		if (!isOpen)
			throw new IOException("Stream closed");
	}

	public static void main(String[] args) {
		ByteBuffer bb = ByteBuffer.allocate(10);
		bb.put((byte) 0x01);
		print(bb);
		bb.put((byte) 0x01);
		print(bb);

	}

	private static void print(ByteBuffer bb) {
		System.out.println("capacity=" + bb.capacity() + ",position="
				+ bb.position() + ",limit=" + bb.limit() + ",remain="
				+ bb.remaining());
	}

}
